package com.beauty.dressing.common.video;

import android.content.Context;
import android.graphics.PointF;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;

import com.beauty.dressing.common.utils.RecyclerViewTool;
import com.beauty.dressing.common.utils.Tools;
import com.framework.common.utils.ILog;

/**
 * Created by Bond on 2016/11/10 19:15
 * you can contact me at qbaowei@qq.com
 * <p>
 * 包裹RecyclerView，悬浮视频播放器
 */


public abstract class BaseListVideoLayout<Player, ScrollableView> extends FrameLayout implements VideoPlayer.ListVideoLayoutListener {

    /**
     * 被跟随布局在列表中的坐标
     */
    private int mFollowViewAdapterPos = -1;

    /**
     * 视频播放器的坐标
     */
    private PointF mPointF = new PointF();

    private VideoPlayer.VideoViewHolderListener mVideoViewHolderListener;

    private ScrollListener mScrollListener = new ScrollListener();

    public BaseListVideoLayout(Context context) {
        super(context);
        init(context, null);
    }

    public BaseListVideoLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public BaseListVideoLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
    }

    protected abstract Player getVideoPlayer();

    protected abstract ScrollableView getScrollableView();

    public boolean isVideoPlayerFollowing() {
        return -1 != mFollowViewAdapterPos;
    }

    public boolean follow(@NonNull VideoPlayer.VideoViewHolderListener videoViewHolderListener) {
        if (null == videoViewHolderListener) {
            ILog.le("[vp]Param videoViewHolderListener is null");
            return false;
        }

        int followViewAdapterPos = videoViewHolderListener.getFollowdViewAdapterPosition();
        ILog.ld("[vp]try to follow video item %d", followViewAdapterPos);
        if (!Tools.checkNetWorkAndToast()) {
            return false;
        }
        if (isSameFollow(followViewAdapterPos)) {
            return false;
        }
        mVideoViewHolderListener = videoViewHolderListener;
        boolean b = onInitVideoPlayer(videoViewHolderListener);
        if (b) {
            startFollow();
        } else {
            stopFollow();
        }
        return b;
    }

    private void startFollow() {
        ILog.ld("[vp]here");
        mFollowViewAdapterPos = mVideoViewHolderListener.getFollowdViewAdapterPosition();
        mPointF = getSpecifiedChildViewPosition(mVideoViewHolderListener.getFollowedView());
        addScrollListener();
        onStarVideoPlayerFollowView();
        updateVideoViewLayoutPosition();
    }

    public void stopFollow() {
        ILog.ld("[vp]here");
        removeScrollListener();
        onStopVideoPlayerFollowView();
        mFollowViewAdapterPos = -1;
        mPointF.set(0, 0);
    }

    private void addScrollListener() {
        removeScrollListener();
        ScrollableView sview = getScrollableView();
        if (sview instanceof RecyclerView) {
            ((RecyclerView) sview).addOnScrollListener(mScrollListener);
        }
    }

    private void removeScrollListener() {
        ScrollableView sview = getScrollableView();
        if (sview instanceof RecyclerView) {
            ((RecyclerView) sview).removeOnScrollListener(mScrollListener);
        }
    }

    public void updateVideoViewLayoutPosition() {
        View mFollowView = mVideoViewHolderListener.getFollowedView();
        if (null == mFollowView) {
            ILog.le("[vp]null == mFollowView");
            return;
        }
        //PointF point = getSpecifiedChildViewPosition(mFollowView);
        Player videoPlayer = getVideoPlayer();
        if (videoPlayer instanceof View) {
            View videoPlayerView = (View) videoPlayer;
            videoPlayerView.setX(mPointF.x);
            videoPlayerView.setY(mPointF.y);
        }
    }

    private boolean isSameFollow(int followViewAdapterPos) {
        boolean b = mFollowViewAdapterPos == followViewAdapterPos;
        if (b) {
            ILog.lw("[vp]Following adapter position %d item now, so ignore holder click event.", mFollowViewAdapterPos);
        }
        return b;
    }

    protected abstract boolean onInitVideoPlayer(VideoPlayer.VideoViewHolderListener videoViewHolderListener);

    protected abstract void onStarVideoPlayerFollowView();

    protected abstract void onStopVideoPlayerFollowView();

    private class ScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int firstVisiblePos = RecyclerViewTool.getRecyclerViewFirstCompleteVisiblePos(recyclerView, false, true)[0];
            int lastVisiblePos = RecyclerViewTool.getRecyclerViewFirstCompleteVisiblePos(recyclerView, false, false)[0];
            ILog.lv("[vp]mFollowViewAdapterPos=%d,firstVisiblePos=%d, lastVisiblePos=%d", mFollowViewAdapterPos, firstVisiblePos, lastVisiblePos);
            if (firstVisiblePos > mFollowViewAdapterPos || lastVisiblePos < mFollowViewAdapterPos) {
                stopFollow();
            } else {
                mPointF.set(mPointF.x, mPointF.y - dy);
                updateVideoViewLayoutPosition();
            }
        }
    }

    @Override
    public BaseListVideoLayout getListVideoLayout() {
        return this;
    }

    //    /**
    //     * 获得状态栏的高度
    //     */
    //    public static int getStatusHeight(Context context) {
    //        int statusHeight = 0;
    //        try {
    //            Class clazz = Class.forName("com.android.internal.R$dimen");
    //            Object object = clazz.newInstance();
    //            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
    //            statusHeight = context.getResources().getDimensionPixelSize(height);
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //            ILog.le(e);
    //            statusHeight = (int) context.getResources().getDimension(R.dimen.status_bar_height);
    //        }
    //        return statusHeight;
    //    }

    /**
     * @param view 必须是子view，切记
     */
    private PointF getSpecifiedChildViewPosition(View view) {
        PointF point = new PointF();
        point.set(view.getX(), view.getY());
        while (true) {
            ViewParent viewParent = view.getParent();
            if (null == viewParent) {
                ILog.le("[vp]viewParent should not be null");
                break;
            }
            ViewGroup parent = (ViewGroup) viewParent;
            point.set(point.x + parent.getX(), point.y + parent.getY());
            if (this == parent) {
                ILog.lv("[vp]get specified child view finished.");
                break;
            }
            view = parent;
        }
        return point;
    }
}
